<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="计划标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入计划标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属部门" prop="departmentId">
        <dept-select
          v-model="queryParams.departmentId"
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工作年份" prop="workYear">
        <el-input
          v-model="queryParams.workYear"
          placeholder="请输入工作年份"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工作季度" prop="workQuarter">
        <el-input
          v-model="queryParams.workQuarter"
          placeholder="请输入工作季度"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['hhsw:workPlan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['hhsw:workPlan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['hhsw:workPlan:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['hhsw:workPlan:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="workPlanList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="计划标题" align="center" prop="title" width="300" />
      <el-table-column label="计划内容" align="center" prop="content" width="400" />
      <el-table-column label="开始时间" align="center" prop="startDate" width="150" />
      <el-table-column label="结束时间" align="center" prop="endDate" width="150" />
      <el-table-column label="当前进度" align="center" width="200">
        <template slot-scope="scope">
          <el-progress 
            :percentage="scope.row.progress" 
            :format="format"
          />
        </template>
      </el-table-column>
      <el-table-column label="所属部门" align="center" prop="departmentId" width="150" />
      <el-table-column label="状态" align="center" prop="status" width="100" />
      <el-table-column label="工作年份" align="center" prop="workYear" width="100" />
      <el-table-column label="工作季度" align="center" prop="workQuarter" width="100" />
      <el-table-column label="操作" align="center" width="180" fixed="right">
        <template slot-scope="scope">
          <!-- 查看按钮 -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['hhsw:workPlan:query']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['hhsw:workPlan:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['hhsw:workPlan:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工作计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" :close-on-click-modal="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="计划标题" prop="title">
          <el-input 
            v-model="form.title" 
            placeholder="请输入计划标题" 
            :readonly="title === '查看工作计划'"
          />
        </el-form-item>
        <el-form-item label="计划内容">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="6"
            placeholder="请输入计划内容"
            :readonly="title === '查看工作计划'"
          />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="所属部门" prop="departmentId">
              <dept-select
                v-model="form.departmentId"
                :disabled="title === '查看工作计划'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建人" prop="creatorId">
              <el-input 
                v-model="form.creatorId" 
                placeholder="请输入创建人" 
                :readonly="title === '查看工作计划'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker 
                v-model="form.startDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择开始日期"
                style="width: 100%"
                :readonly="title === '查看工作计划'"
                :disabled="title === '查看工作计划'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker 
                v-model="form.endDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择结束日期"
                style="width: 100%"
                :readonly="title === '查看工作计划'"
                :disabled="title === '查看工作计划'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="总体进度" prop="progress">
          <el-row :gutter="10" type="flex" align="middle">
            <el-col :span="20">
              <el-progress 
                :percentage="form.progress" 
                :format="format"
                @click.native="handlePlanProgressClick"
                style="cursor: pointer"
              />
            </el-col>
            <el-col :span="4" style="text-align: right">
              <el-button 
                type="primary" 
                size="mini" 
                icon="el-icon-edit"
                @click="handlePlanProgressClick"
                v-if="title !== '查看工作计划'"
              >修改</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工作年份" prop="workYear">
              <el-input 
                v-model="form.workYear" 
                placeholder="请输入工作年份" 
                :readonly="title === '查看工作计划'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作季度" prop="workQuarter">
              <el-input 
                v-model="form.workQuarter" 
                placeholder="请输入工作季度" 
                :readonly="title === '查看工作计划'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="form.remark" 
            type="textarea" 
            placeholder="请输入内容" 
            :readonly="title === '查看工作计划'"
          />
        </el-form-item>

        <!-- 添加进度节点部分 -->
        <el-form-item label="进度节点">
          <el-table :data="planNodes" border style="width: 100%">
            <el-table-column label="节点名称" prop="nodeName" width="150" />
            <el-table-column label="节点描述" prop="description" />
            <el-table-column label="截止时间" prop="deadline" width="100">
              <template slot-scope="scope">
                <span>{{ scope.row.deadline }}</span>
              </template>
            </el-table-column>
            <el-table-column label="进度" prop="nodeProgress" width="120">
              <template slot-scope="scope">
                <el-progress 
                  :percentage="scope.row.nodeProgress" 
                  :format="format"
                  @click.native="handleProgressClick(scope.row)"
                  style="cursor: pointer"
                />
              </template>
            </el-table-column>
            <el-table-column label="状态" prop="isCompleted" width="80">
              <template slot-scope="scope">
                <el-tag :type="scope.row.isCompleted === 1 ? 'success' : 'warning'">
                  {{ scope.row.isCompleted === 1 ? '已完成' : '进行中' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime" width="150" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.createTime }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="150" v-if="title !== '查看工作计划'">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="handleEditNode(scope.row)">编辑</el-button>
                <el-button size="mini" type="text" @click="handleDeleteNode(scope.row)" style="color: #F56C6C">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top: 10px; text-align: right" v-if="title !== '查看工作计划'">
            <el-button type="primary" size="small" @click="handleAddNode">添加节点</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="title !== '查看工作计划'">确 定</el-button>
        <el-button @click="cancel">{{ title === '查看工作计划' ? '关 闭' : '取 消' }}</el-button>
      </div>
    </el-dialog>

    <!-- 添加进度节点对话框 -->
    <el-dialog :title="nodeDialogTitle" :visible.sync="nodeDialogVisible" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="nodeForm" :model="nodeForm" :rules="nodeRules" label-width="100px">
        <el-form-item label="节点名称" prop="nodeName">
          <el-input v-model="nodeForm.nodeName" placeholder="请输入节点名称" />
        </el-form-item>
        <el-form-item label="节点描述" prop="description">
          <el-input v-model="nodeForm.description" type="textarea" placeholder="请输入节点描述" />
        </el-form-item>
        <el-form-item label="截止时间" prop="deadline">
          <el-date-picker
            v-model="nodeForm.deadline"
            type="date"
            placeholder="选择截止日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="完成进度" prop="nodeProgress">
          <el-slider 
            v-model="nodeForm.nodeProgress" 
            :step="10"
            :marks="{
              0: '0%',
              20: '20%',
              40: '40%',
              60: '60%',
              80: '80%',
              100: '100%'
            }"
          ></el-slider>
        </el-form-item>
        <el-form-item label="是否完成" prop="isCompleted">
          <el-switch 
            v-model="nodeForm.isCompleted"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitNodeForm">确 定</el-button>
        <el-button @click="cancelNode">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加总体进度编辑对话框 -->
    <el-dialog title="编辑总体进度" :visible.sync="planProgressDialogVisible" width="400px" append-to-body :close-on-click-modal="false">
      <el-form :model="planProgressForm" label-width="80px">
        <el-form-item label="进度">
          <el-slider 
            v-model="planProgressForm.progress" 
            :step="10"
            :marks="{
              0: '0%',
              20: '20%',
              40: '40%',
              60: '60%',
              80: '80%',
              100: '100%'
            }"
          ></el-slider>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPlanProgress">确 定</el-button>
        <el-button @click="planProgressDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listWorkPlan, getWorkPlan, delWorkPlan, addWorkPlan, updateWorkPlan } from "@/api/hhsw/workPlan";
import { listPlanNode, getPlanNode, delPlanNode, addPlanNode, updatePlanNode } from "@/api/hhsw/planNode";
import DeptSelect from "@/components/DeptSelect";

export default {
  name: "WorkPlan",
  components: {
    DeptSelect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工作计划表格数据
      workPlanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        content: null,
        departmentId: null,
        creatorId: null,
        startDate: null,
        endDate: null,
        progress: null,
        status: null,
        workYear: null,
        workQuarter: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "计划标题不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "计划内容不能为空", trigger: "blur" }
        ],
        departmentId: [
          { required: true, message: "所属部门不能为空", trigger: "blur" }
        ],
        creatorId: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "开始日期不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "结束日期不能为空", trigger: "blur" }
        ],
        progress: [
          { required: true, message: "当前进度不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        workYear: [
          { required: true, message: "工作年份不能为空", trigger: "blur" }
        ],
        workQuarter: [
          { required: true, message: "工作季度不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建者不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      },
      // 进度节点相关
      planNodes: [],
      nodeDialogTitle: "",
      nodeDialogVisible: false,
      nodeForm: {
        id: null,
        planId: null,
        nodeName: '',
        description: '',
        deadline: '',
        nodeProgress: 0,
        isCompleted: 0
      },
      nodeRules: {
        nodeName: [
          { required: true, message: '请输入节点名称', trigger: 'blur' }
        ],
        deadline: [
          { required: true, message: '请选择截止日期', trigger: 'blur' }
        ]
      },
      planProgressDialogVisible: false,
      planProgressForm: {
        progress: 0
      },
      currentNode: null
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询工作计划列表 */
    getList() {
      this.loading = true;
      listWorkPlan(this.queryParams).then(response => {
        this.workPlanList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        content: null,
        departmentId: null,
        creatorId: null,
        startDate: null,
        endDate: null,
        progress: null,
        status: null,
        workYear: null,
        workQuarter: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids
      getWorkPlan(id).then(response => {
        this.form = response.data;
        this.getNodeList(id); // 加载进度节点
        this.open = true;
        this.title = "查看工作计划";
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加工作计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getWorkPlan(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改工作计划";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWorkPlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addWorkPlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除工作计划编号为"' + ids + '"的数据项？').then(function() {
        return delWorkPlan(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('hhsw/workPlan/export', {
        ...this.queryParams
      }, `workPlan_${new Date().getTime()}.xlsx`)
    },
    // 获取进度节点列表
    getNodeList(planId) {
      listPlanNode({ planId: planId }).then(response => {
        this.planNodes = response.rows;
      });
    },
    // 添加节点
    handleAddNode() {
      this.nodeForm = {
        planId: this.form.id,
        nodeName: '',
        description: '',
        deadline: '',
        nodeProgress: 0,
        isCompleted: 0
      };
      this.nodeDialogTitle = '添加进度节点';
      this.nodeDialogVisible = true;
    },
    // 编辑节点
    handleEditNode(row) {
      this.nodeForm = JSON.parse(JSON.stringify(row));
      this.nodeDialogTitle = '编辑进度节点';
      this.nodeDialogVisible = true;
    },
    // 删除节点
    handleDeleteNode(row) {
      this.$modal.confirm('确认删除该进度节点吗？').then(() => {
        return delPlanNode(row.id);
      }).then(() => {
        this.getNodeList(this.form.id);
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 提交节点表单
    submitNodeForm() {
      this.$refs.nodeForm.validate(valid => {
        if (valid) {
          if (this.nodeForm.id != null) {
            updatePlanNode(this.nodeForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.nodeDialogVisible = false;
              this.getNodeList(this.form.id);
            });
          } else {
            addPlanNode(this.nodeForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.nodeDialogVisible = false;
              this.getNodeList(this.form.id);
            });
          }
        }
      });
    },
    // 取消节点编辑
    cancelNode() {
      this.nodeDialogVisible = false;
      this.nodeForm = {
        id: null,
        planId: null,
        nodeName: '',
        description: '',
        deadline: '',
        nodeProgress: 0,
        isCompleted: 0
      };
    },
    // 格式化进度显示
    format(percentage) {
      return percentage + '%';
    },
    // 点击进度条时的处理
    handleProgressClick(row) {
      if (this.title === '查看工作计划') return;
      this.currentNode = row;
      this.planProgressForm.progress = row.nodeProgress;
      this.planProgressDialogVisible = true;
    },
    // 提交进度更新
    submitPlanProgress() {
      const updatedNode = {
        ...this.currentNode,
        nodeProgress: this.planProgressForm.progress,
        isCompleted: this.planProgressForm.progress === 100 ? 1 : 0
      };
      
      updatePlanNode(updatedNode).then(response => {
        this.$modal.msgSuccess("进度更新成功");
        this.planProgressDialogVisible = false;
        this.getNodeList(this.form.id);
      });
    },
    // 点击总体进度条时的处理
    handlePlanProgressClick() {
      if (this.title === '查看工作计划') return;
      this.planProgressForm.progress = this.form.progress || 0;
      this.planProgressDialogVisible = true;
    },
    // 提交总体进度更新
    submitPlanProgress() {
      const updatedPlan = {
        ...this.form,
        progress: this.planProgressForm.progress
      };
      
      updateWorkPlan(updatedPlan).then(response => {
        this.$modal.msgSuccess("进度更新成功");
        this.planProgressDialogVisible = false;
        this.form.progress = this.planProgressForm.progress;
      });
    }
  }
};
</script>
